<!--
  @author:  long
  @date:    2023/5/31
  @file:    xx
  @require:
-->
<template>
  <div>
    <FixedOperation>
      <div class="flex items-center justify-between">
        <span>绩效申诉</span>
        <!-- 内容 -->
        <div class="text-right">
          <slot></slot>
          <!--          <el-button type="primary" @click="handleSave">保存</el-button>-->
          <el-button type="danger" @click="close">关闭</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="appealForm app-container">
      <div class="px-20">
        <el-form
          label-width="100"
          :model="form"
          :rules="rules"
          ref="ruleFormRef"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="申诉人：" required>
                {{ appealerNickName }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职务：" required>
                {{ userInfo.job }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="岗位：" required>
                {{ userInfo.position }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部门：" required>
                {{ userInfo.deptName }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申诉事件：" prop="appealTitle">
                {{ form.appealTitle }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申诉理由：" prop="appealContent">
                {{ form.appealContent }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件：">
                <!--                                <el-upload-->
                <!--                                    class="upload-demo"-->
                <!--                                    action="#"-->
                <!--                                    :http-request="-->
                <!--                    params => {-->
                <!--                      handleFileChange(params)-->
                <!--                    }-->
                <!--                  "-->
                <!--                                    accept=".rar, .zip, .doc, .docx, .pdf,.png,.jpg,.jpeg"-->
                <!--                                    :show-file-list="false"-->
                <!--                                >-->
                <!--                                    <el-button type="primary" style="font-size: 14px"-->
                <!--                                    ><el-icon><UploadFilled /></el-icon>上传附件</el-button-->
                <!--                                    >-->
                <!--                                    <template #tip>-->
                <!--                                        <div class="el-upload__tip">-->
                <!--                                            支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB-->
                <!--                                        </div>-->
                <!--                                    </template>-->
                <!--                                </el-upload>-->
                <div class="text-14px mt-10px" style="width: 100%">
                  <div v-for="item in fileList" :key="item.fileId">
                    <a :href="item.url">{{ item.origFileName }}</a>
                    <!--                                        <el-button text plain @click="delFileName(index, 'file')"-->
                    <!--                                        >删除</el-button-->
                    <!--                                        >-->
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="flex items-center justify-between mb-3">
        <TitleName
          title="关联绩效指标"
          icon="i-carbon-bookmark-filled"
        ></TitleName>
      </div>
      <div class="selfAppealList">
        <el-table :data="selectTableData" border>
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            label="一级指标"
            fixed="left"
            prop="firstLevel"
            width="150"
          ></el-table-column>
          <el-table-column
            label="二级指标"
            fixed="left"
            prop="secondLevel"
            width="150"
          ></el-table-column>
          <el-table-column
            label="指标说明及工作内容、工作要求等"
            width="320"
            show-overflow-tooltip
            fixed="left"
            prop="content"
          ></el-table-column>
          <el-table-column label="指标单位" width="100" prop="unit">
          </el-table-column>
          <el-table-column
            label="指标值"
            width="100"
            prop="targetValue"
          ></el-table-column>
          <el-table-column
            label="考核评分标准"
            show-overflow-tooltip
            width="200"
            prop="scoreStandard"
          ></el-table-column>

          <el-table-column
            label="自评完成情况"
            width="130"
            prop="scoreDescriptionSelf"
          >
          </el-table-column>
          <el-table-column label="备注说明" width="130" prop="remark">
          </el-table-column>
          <el-table-column
            label="分值权重"
            width="100"
            prop="score"
            fixed="right"
          ></el-table-column>
          <el-table-column
            label="自评得分"
            align="center"
            fixed="right"
            prop="finalScoreSelf"
            width="80"
            v-if="!isHandleScore"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="原考核得分"
            align="center"
            width="100"
            prop="finalScore"
            v-if="!isHandleScore"
          ></el-table-column>
          <el-table-column
            fixed="right"
            label="重评完成情况"
            align="center"
            width="130"
            prop="scoreDescriptionAp"
            v-if="isHandleScore"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.scoreDescriptionAp"
                :type="scope.row.scoreMethod == '2' ? 'number' : 'text'"
                @input="
                  val => {
                    scoreDescriptionSelfInput(val, scope.row)
                  }
                "
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="重评得分"
            align="center"
            width="200"
            prop="scoreAp"
            v-if="isHandleScore"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.scoreAp"
                v-if="scope.row.scoreMethod == '1'"
                @change="
                  val => {
                    scoreInputChange(scope.row, val)
                  }
                "
              ></el-input>
              <el-input-number
                v-else
                :min="
                  scope.row.scoreMethod == '1'
                    ? scope.row.score == '减分项' ||
                      scope.row.score == '加/减分项'
                      ? -9999
                      : 0
                    : 0
                "
                :max="
                  scope.row.scoreMethod == '3'
                    ? scope.row.score - scope.row.basicScore
                    : scope.row.scoreMethod == '1'
                    ? scope.row.scope == '加分项'
                      ? 9999
                      : scope.row.score * 1
                    : scope.row.score * 1
                "
                v-model="scope.row.scoreAp"
                :disabled="scope.row.scoreMethod == '2'"
                @input="
                  val => {
                    handleGradeBlur(scope.row, val)
                  }
                "
                @change="
                  val => {
                    handleGradeInput(scope.row, val)
                  }
                "
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="重评得分"
            align="center"
            width="80"
            prop="finalScoreAp"
            v-if="isHandleScore"
          ></el-table-column>
          <el-table-column
            v-if="isConfirm"
            fixed="right"
            label="重评最终得分"
            align="center"
            width="110"
            prop="totalScoreAp"
          ></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup name="examineAppealEdit">
import { getCurrentInstance } from 'vue'
import useUserStore from '@/store/modules/user'
import useTagsViewStore from '@/store/modules/tagsView'
import { useRouter } from 'vue-router'
import { isNumberStr } from '@/utils'

const userStore = useUserStore()
const router = useRouter()
import { format } from 'date-fns'
import { getUserInfoByUserName } from '@/api/system/user'
import {
  editBizassessappealInfo,
  getBizassessappealAppealinfo,
  saveBizassessappealInfo
} from '@/api/officeManage/appeal'
import { getDept, getListWithRole } from '@/api/system/dept'
import { getNodeData } from '@/api/workflow/process'

const { proxy } = getCurrentInstance()

const props = defineProps({
  id: {
    type: String,
    default: ''
  }
})

const data = reactive({
  queryForm: {
    year: format(new Date(new Date().getTime()), 'yyyy'),
    month: format(new Date(new Date().getTime()), 'MM')
  },
  form: {
    appealTitle: '',
    appealContent: ''
  },
  userInfo: {},
  rules: {
    appealTitle: [
      { required: true, message: '请输入申诉事件', trigger: 'blur' }
    ],
    appealContent: [
      { required: true, message: '请输入申诉理由', trigger: 'blur' }
    ]
  },
  monthNames: [
    { label: '一月', value: '01' },
    { label: '二月', value: '02' },
    { label: '三月', value: '03' },
    { label: '四月', value: '04' },
    { label: '五月', value: '05' },
    { label: '六月', value: '06' },
    { label: '七月', value: '07' },
    { label: '八月', value: '08' },
    { label: '九月', value: '09' },
    { label: '十月', value: '10' },
    { label: '十一月', value: '11' },
    { label: '十二月', value: '12' }
  ],
  fileList: [], // 上传文件列表
  alternateLoading: false
})
const {
  form,
  userInfo,
  rules,
  fileList,
  monthNames,
  queryForm,
  alternateLoading
} = toRefs(data)
const dialogVisible = ref(false) //弹窗开关
const alternateTableData = ref([]) //备选指标
const selectTableData = ref([]) //已选指标
const appealId = ref('') //申诉id
const scoreList = ref([])
const appealerNickName = ref('')
const appealerUserName = ref('')

const examineParam = ref({}) //审批弹窗参数
const isExamine = ref(true) //流程是判断是否走审批按钮
const flowOptions = ref([]) //该业务的流程数据
const isHandleScore = ref(false) // 判断是否在重评节点
const isConfirm = ref(false) //申诉人确认阶段

/**
 * @description: 录入情况下评分input框change方法
 */
const scoreInputChange = (row, val) => {
  if (!isNumberStr(val) && val != '') {
    proxy.$modal.msgError('请输入数字，最多保留两位小数')
    row.scoreAp = null
    handleGradeInput(row, null)
  } else if (val == '') {
    handleGradeInput(row, null)
  } else {
    let inputVal = val * 1
    switch (row.score) {
      //加分项
      case '加分项':
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.scoreAp = null

          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      //加减分项
      case '加/减分项':
        handleGradeInput(row, val)
        break
      //减分项
      case '减分项':
        if (inputVal > 0) {
          proxy.$modal.msgError('请输入负数或0，最多保留两位小数')
          row.scoreAp = null

          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      default:
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.scoreAp = null

          handleGradeInput(row, null)
        } else if (inputVal > row.score * 1) {
          row.scoreAp = row.score
          handleGradeInput(row, row.score)
        } else {
          handleGradeInput(row, val)
        }
        break
    }
  }
}

const handleGradeBlur = (row, val) => {
  if (val === null) {
    row.finalScoreAp = ''
    return
  }
}
/**
 * @description: 评分输入框input方法
 */
const handleGradeInput = (row, val) => {
  if (val === null) {
    row.finalScoreAp = ''
    return
  }
  let inputVal = val * 1
  switch (row.scoreMethod) {
    //录入
    case '1':
      row.finalScoreAp = inputVal
      break
    // 完成率
    case '2':
      row.finalScoreAp = inputVal
      break
    //加分
    case '3':
      row.finalScoreAp = row.basicScore + inputVal
      break
    //减分
    case '4':
      console.info('val', val)
      console.info('row.score', row.score)
      console.info('row.score - inputVal', row.score - inputVal)
      console.info('final_score_self', row.finalScoreAp)
      row.finalScoreAp = row.score - inputVal
      break

    default:
      break
  }
}

//计算评分
const scoreDescriptionSelfInput = (val, row) => {
  if (row.scoreMethod == '2') {
    //   计算百分比
    let percentage =
      Math.round(((row.scoreDescriptionAp * 1) / row.targetValue) * 10000) / 100
    console.info('row.scoreStandardCode', row.scoreStandardCode)
    let rate = percentage * 0.01
    switch (row.scoreStandardCode) {
      case '1':
        if (percentage >= 60) {
          row.scoreAp =
            rate * row.score > row.score ? row.score : rate * row.score
        } else {
          row.scoreAp = 0
        }
        break
      case '2':
        if (percentage >= 60) {
          row.scoreAp =
            rate * row.score > row.score ? row.score : rate * row.score
        } else if (percentage == 0) {
          row.scoreAp = 0 - row.score
        } else {
          row.scoreAp = 0
        }
        break
      case '3':
        row.scoreAp =
          rate * row.score > row.score ? row.score : rate * row.score
        break
      case '4':
        if (percentage >= 60) {
          row.scoreAp =
            rate * row.score > row.score ? row.score : rate * row.score
        } else if (percentage == 0) {
          row.scoreAp = 0 - row.score
        } else {
          row.scoreAp = 0
        }
        break
      case '5':
        if (percentage >= 60) {
          row.scoreAp =
            rate * row.score > row.score * 1.2
              ? row.score * 1.2
              : rate * row.score
        } else {
          row.scoreAp = 0
        }
        break
      case '6':
        if (percentage >= 60) {
          row.scoreAp =
            rate * row.score > row.score * 1.3
              ? row.score * 1.3
              : rate * row.score
        } else {
          row.scoreAp = 0
        }
        break
    }
    console.info(' row.scoreSelf', row.scoreAp)
    row.scoreAp = row.scoreAp.toFixed(2)

    handleGradeInput(row, row.scoreAp)
  }
}

/**
 * 获取当前流程节点信息
 */
const getNodeDataInfo = () => {
  getNodeData(props.id).then(res => {
    if (res.data.nowTaskName == '重新考评') {
      isHandleScore.value = true
    }
    if (
      res.data.nowTaskName == '申诉人确认' ||
      res.data.nowTaskName == '审批通过'
    ) {
      isConfirm.value = true
    }
  })
}

/**
 * 获取申诉信息
 */
const getAppealInfoFn = () => {
  let id = appealId.value
  getBizassessappealAppealinfo(id).then(res => {
    form.value.appealTitle = res.data.appealTitle
    form.value.appealContent = res.data.appealContent
    appealerUserName.value = res.data.appealerUserName
    scoreList.value = res.data.scoreList
    //   考核人进入看到的指标信息与申诉人进入看到的指标信息使用字段不一致
    let arr = res.data.indicatorsList
    if (arr.length > 0) {
      arr.forEach(item => {
        let obj = res.data.appealIndicatorsList.find(
          t => t.indicatorsId == item.id
        )
        if (isHandleScore.value) {
          item.scoreDescriptionAp = ''
          item.scoreAp = null
          item.finalScoreAp = ''
        }
        item.finalScoreSelf = obj.selfScore
        item.finalScore = obj.totalScore
        item.appraiseeId = obj.appraiseeId
        item.indicatorsId = obj.id
        item.totalScoreAp = obj.totalScoreAp
      })
    }
    selectTableData.value = arr
    console.info('selectTableData.value', selectTableData.value)
    fileList.value = res.data.fileList
    appealerNickName.value = res.data.appealerNickName
    getUserInfo(res.data.appealerUserName)
  })
}

watch(
  () => props.id,
  async val => {
    if (
      (val && !!location.href.match(/detail/)) ||
      (val && !!location.href.match(/workDetail/))
    ) {
      // 待办详情-访问
      examineParam.value.businessId = val
      appealId.value = val
      await getNodeDataInfo()
      await getAppealInfoFn()
    }
  },
  {
    immediate: true
  }
)

/*
 * 保存
 */
const handleSave = () => {
  return new Promise((resolve, reject) => {
    try {
      console.info('selectTableData.value', selectTableData.value)
      //    判断是否进行得分重评
      if (isHandleScore.value) {
        let index = selectTableData.value.findIndex(
          item => item.scoreAp == null || item.scoreAp == ''
        )
        if (index != -1) {
          let msgStr = `第${index + 1}行指标未进行得分重评，请进行得分重评`
          proxy.$modal.msgWarning(msgStr)
          return
        }
        //   处理指标信息
        let detailList = selectTableData.value.map(item => {
          return {
            appraiseeId: item.appraiseeId,
            totalScore: item.finalScore,
            selfScore: item.finalScoreSelf,
            indicatorsId: item.id
          }
        })
        let params = {
          appealContent: form.value.appealContent,
          appealTitle: form.value.appealTitle,
          appealerId: selectTableData.value[0].appraiseeId,
          appealerUserName: appealerUserName.value,
          detaillist: detailList
          // fileName: fileName
        }
        if (isHandleScore.value) {
          let list = scoreList.value.map(item => {
            if (item.assessorId == userStore.user.userId) {
              let obj = selectTableData.value.find(t => {
                return t.indicatorsId == item.appealIndicatorsRefId
              })
              item.finalScoreAp = obj.finalScoreAp
              item.scoreAp = obj.scoreAp
              item.scoreDescriptionAp = obj.scoreDescriptionAp
            }

            return item
          })
          params.scoreList = list
        }
        // 修改
        params.id = appealId.value
        editBizassessappealInfo(params).then(res => {
          if (res.code === 200) {
            // proxy.$modal.msgSuccess('修改成功')
            resolve()
          }
        })
      } else {
        resolve()
      }
      console.info('3456', userInfo.value)

      //   处理附件
      // let fileName =
      //   fileList.value && fileList.value.length > 0
      //     ? fileList.value.map(item => {
      //         return item.fileName
      //       })
      //     : []
    } catch (e) {
      reject(e)
    }
  })
}

// 将 handleSave 暴露
defineExpose({
  handleSave
})

/**
 * 返回
 */
const close = () => {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

/**
 * 获取用户信息
 */
const getUserInfo = userName => {
  // userInfo.value = userStore.user
  let userCode = userName || userStore.user.userName

  getUserInfoByUserName(userCode).then(res => {
    userInfo.value = res.data
    let params = {
      deptId: userInfo.value.deptId
    }
    getListWithRole(params).then(response => {
      userInfo.value.deptName = response.data[0].deptName
    })
  })
}
</script>

<style scoped lang="scss">
:deep(.monthPopper) {
  width: 300px !important;
}

.monthPopper .el-select-dropdown__item {
  width: 25%;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  padding: 0;
}

::v-deep .appealDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
}
</style>
